<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
use App\Models\Product;
use App\Models\Order;
use App\Models\User;
use App\Models\Category;
use Illuminate\Support\Facades\DB;

class AdminDashboardController extends Controller
{
    /**
     * 显示仪表板
     */
    public function index(): Response
    {
        // 获取统计数据
        $stats = [
            'totalSales' => $this->getTotalSales(),
            'totalOrders' => Order::count(),
            'totalProducts' => Product::where('is_active', true)->count(),
            'totalUsers' => User::count(),
            'todaySales' => $this->getTodaySales(),
            'todayOrders' => $this->getTodayOrders(),
            'pendingOrders' => $this->getPendingOrders(),
            'lowStockProducts' => $this->getLowStockCount(),
        ];

        // 获取热门产品（按实际销量排序）
        $topProducts = $this->getTopProducts();

        // 获取最近订单
        $recentOrders = Order::with(['user'])
            ->orderBy('created_at', 'desc')
            ->limit(10)
            ->get()
            ->map(function ($order) {
                return [
                    'id' => $order->id,
                    'order_number' => $order->order_number,
                    'user' => $order->user,
                    'total_amount' => $order->total_amount,
                    'status' => $order->status,
                    'created_at' => $order->created_at,
                ];
            });

        // 获取销售趋势数据（最近7天）
        $salesTrend = $this->getSalesTrend(7);

        // 获取订单状态分布
        $orderStatusDistribution = $this->getOrderStatusDistribution();

        // 获取分类销售统计（Top 5）
        $categorySales = $this->getCategorySales();

        // 获取库存警告产品
        $lowStockProducts = $this->getLowStockProducts();

        return Inertia::render('Admin/Dashboard', [
            'stats' => $stats,
            'topProducts' => $topProducts,
            'recentOrders' => $recentOrders,
            'salesTrend' => $salesTrend,
            'orderStatusDistribution' => $orderStatusDistribution,
            'categorySales' => $categorySales,
            'lowStockProducts' => $lowStockProducts,
        ]);
    }

    /**
     * 获取总销售额
     */
    private function getTotalSales(): float
    {
        return Order::where('payment_status', 'paid')
            ->sum('total_amount');
    }

    /**
     * 获取热门产品（按销量排序）
     */
    private function getTopProducts(): array
    {
        $topProducts = DB::table('order_items')
            ->join('products', 'order_items.product_id', '=', 'products.id')
            ->select(
                'products.id',
                'products.name',
                'products.price',
                DB::raw('SUM(order_items.quantity) as sales_count')
            )
            ->where('products.is_active', true)
            ->groupBy('products.id', 'products.name', 'products.price')
            ->orderBy('sales_count', 'desc')
            ->limit(5)
            ->get()
            ->toArray();

        // 如果没有销售数据，返回一些活跃产品
        if (empty($topProducts)) {
            $topProducts = Product::where('is_active', true)
                ->limit(5)
                ->get()
                ->map(function ($product) {
                    return [
                        'id' => $product->id,
                        'name' => $product->name,
                        'price' => $product->price,
                        'sales_count' => 0,
                    ];
                })
                ->toArray();
        }

        return $topProducts;
    }

    /**
     * 获取今日销售额
     */
    private function getTodaySales(): float
    {
        return Order::where('payment_status', 'paid')
            ->whereDate('created_at', today())
            ->sum('total_amount');
    }

    /**
     * 获取今日订单数
     */
    private function getTodayOrders(): int
    {
        return Order::whereDate('created_at', today())->count();
    }

    /**
     * 获取待处理订单数
     */
    private function getPendingOrders(): int
    {
        return Order::where('status', 'pending')->count();
    }

    /**
     * 获取低库存产品数量
     */
    private function getLowStockCount(): int
    {
        return Product::where('is_active', true)
            ->whereRaw('stock_quantity <= low_stock_threshold')
            ->count();
    }

    /**
     * 获取销售趋势数据
     */
    private function getSalesTrend(int $days): array
    {
        $trend = [];
        for ($i = $days - 1; $i >= 0; $i--) {
            $date = now()->subDays($i);
            $sales = Order::where('payment_status', 'paid')
                ->whereDate('created_at', $date)
                ->sum('total_amount');
            $orders = Order::whereDate('created_at', $date)->count();
            
            $trend[] = [
                'date' => $date->format('m-d'),
                'sales' => (float) $sales,
                'orders' => $orders,
            ];
        }
        return $trend;
    }

    /**
     * 获取订单状态分布
     */
    private function getOrderStatusDistribution(): array
    {
        $distribution = Order::select('status', DB::raw('COUNT(*) as count'))
            ->groupBy('status')
            ->get()
            ->mapWithKeys(function ($item) {
                return [$item->status => $item->count];
            })
            ->toArray();

        // 确保所有状态都有值
        $allStatuses = ['pending', 'processing', 'shipped', 'delivered', 'cancelled'];
        foreach ($allStatuses as $status) {
            if (!isset($distribution[$status])) {
                $distribution[$status] = 0;
            }
        }

        return $distribution;
    }

    /**
     * 获取分类销售统计
     */
    private function getCategorySales(): array
    {
        $sales = DB::table('order_items')
            ->join('products', 'order_items.product_id', '=', 'products.id')
            ->join('product_categories', 'products.id', '=', 'product_categories.product_id')
            ->join('categories', 'product_categories.category_id', '=', 'categories.id')
            ->select(
                'categories.name',
                DB::raw('SUM(order_items.quantity) as total_quantity'),
                DB::raw('SUM(order_items.total_amount) as total_sales')
            )
            ->groupBy('categories.id', 'categories.name')
            ->orderBy('total_sales', 'desc')
            ->limit(5)
            ->get()
            ->toArray();

        return $sales;
    }

    /**
     * 获取低库存产品列表
     */
    private function getLowStockProducts(): array
    {
        return Product::where('is_active', true)
            ->whereRaw('stock_quantity <= low_stock_threshold')
            ->select('id', 'name', 'sku', 'stock_quantity', 'low_stock_threshold')
            ->orderBy('stock_quantity', 'asc')
            ->limit(10)
            ->get()
            ->toArray();
    }
}
